from datetime import datetime
from os import path,makedirs,listdir
import requests
from time import localtime, strftime
from ShootSystem.database import OperateDatabase
from playsound import playsound
from PyQt5.QtCore import Qt, QElapsedTimer
from PyQt5.QtWidgets import QApplication, QLabel, QDialog

from model.bud_model.prebud import get_bud
from model.water_model.prewater import get_water

t=localtime()
now_date=strftime("%y%m%d",t)
#i = datetime.now()  #获取当前时间
#print('今天是{}年{}月{}日{}点{}分{}秒'.format(i.year,i.month,i.day,i.hour,i.minute,i.second))

save_path_dir=f'picture/{now_date}/'#{i.year}-{i.month}-{i.day}
#shoot_command_path_dir=f'command/{i.year}-{i.month}-{i.day}/'

def create_dir(save_dir=save_path_dir):
    if not path.exists(save_dir):
        print('不存在文件夹')
        makedirs(save_dir)

# if not path.exists(shoot_command_path_dir):
#     print('不存在文件夹')
#     makedirs(shoot_command_path_dir)

def exist_img(i):
    img_path=save_path_dir+f'{i}.png'#f'({i}).png'
    return img_path,path.exists(img_path)

def find_max_num():
    files = listdir(save_path_dir)
    max=0
    for file in files:
        num = float(file.replace('.png',''))#原.split('(')[1].split(')')[0]
        if num > max:
            max = num
    return max

# def find_command():
#     if not path.exists(shoot_command_path_dir+'stop.txt'):
#         return 1
#     else:
#         return 0
# post
def post_file(filename,mode='test.py'):
    #token = get_token()
    if mode=='remote':
        post_file_url = 'https://h7153156i4.zicp.fun/upload'
    elif mode=='test.py':
        post_file_url = 'http://127.0.0.1:8888/upload'#s
    else:
        post_file_url = 'http://192.168.199.213:8888/upload'
    # headers = {
    #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36'
    #     , 'Accept-Language': 'zh-CN,zh;q=0.9', 'Accept-Encoding': 'gzip, deflate'}#, 'token': 'token'

    send_flag=False

    files = {"file": open(filename, 'rb'), "Content-Type": "text/html; charset=utf-8",
              "filename": filename}#"Content-Disposition": "form-data",
    try:
      requests.post(url=post_file_url, files=files, verify=True)#, headers=headers verify=False
      print('上传成功')
      send_flag=True
    except Exception as e:
         print('连接失败')
         print(e)

    return send_flag

def get_time():
    current_time = datetime.now()
    return str(current_time).split('.')[0]

def get_hms():
    t = localtime()  # 格式化格式
    hms = strftime("%H.%M%S", t)
    return hms

def get_date():
    t = localtime()  # 格式化格式
    date = strftime("%y%m%d", t)
    return date

from random import random, uniform,choice
def generate_data(img_path):

    ds = get_time()  # '2022-10-23 00:00:00'
    moisture_content = round(get_water(img_path),3)#format(get_water(img_path), '.3f')#random()
    tender_bud_num = round(get_bud(img_path))#tender_bud_rate=format(get_bud(img_path), '.0f')#random() '.3f'
    air_temperature = round(uniform(10, 34),1)#format(uniform(10, 34), '.1f')#choice([13,35,18])
    air_humidity = round(random(), 3)#format(random(), '.3f')
    data = [ds, moisture_content, tender_bud_num, air_temperature, air_humidity]
    return data

def init_database():
    setting = {
        'host': 'mysql.sqlpub.com',  # 10.0.24.5 localhost
        'user': 'teamonitor',  #root
        'password': '0249a15c3d72f4aa',  # 1234
        'port': 3306,
        'charset': 'utf8mb4',
        'database': '',  # 默认是None或''，可以对所有数据库操作
        'autocommit': True  # 提交，插入、删除和更新数据库才会生效
    }

    db = OperateDatabase(setting)
    db.use_database('teamonitor')

    return db

from sys import exit
def send_warn(new='温度异常!',sec=5):
    #try:
        app = QApplication([])
        dialog = QDialog()
        dialog.setWindowTitle('警告')
        dialog.setWindowFlags(Qt.WindowTitleHint | Qt.WindowCloseButtonHint)  # 显示标题和关闭按钮
        label = QLabel(dialog)
        label.setAlignment(Qt.AlignCenter)
        label.setText(new+f'({sec}s)')
        label.setStyleSheet('font-size: 20px;')
        label.adjustSize()
        dialog.adjustSize()
        dialog.show()

        timer = QElapsedTimer()
        timer.start()
        while timer.elapsed() < sec * 1000:
            remaining_time = (sec * 1000 - timer.elapsed()) // 1000
            label.setText(new+f'({remaining_time}s)')#str(remaining_time)
            QApplication.processEvents()
            playsound('sound/warn.wav')

        #label.close()
        #app.exec()#循环
        #app.quit()
        exit(1)

    # except Exception as e:
    #     print(e)
    #     print('弹窗报错')

if __name__=='__main__':
    filename=r'E:\program\PycharmProjects\web\wb'#E:\program\PycharmProjects\web\TeaMonitor\static\img\2023-3-30\(1).png
    #post_file(filename)
    db=init_database()
    data=generate_data(r'E:\program\PycharmProjects\web\teamonitor-master\ShootSystem\model\bud_model\24.jpg')
    db.insert_history(data)
    #send_warn(sec=10)
